import {
	defineStore
} from 'pinia'
import api from '@/api/app.js'

const tokenKey = 'YUANZU_TOKEN'
const hasMobileKey = 'YUANZU_HASMOBILE'
const openidKey = 'YUANZU_OPENID'
const userInfoKey = 'YUANZU_USERINFO'

const useAppStore = defineStore('app', () => {
    const userInfo = ref(uni.getStorageSync(userInfoKey) || {})
	const token = ref(uni.getStorageSync(tokenKey))
	const openid = ref(null)
	const isLogin = computed(() => !!token.value)
	const hasMobile = ref(!!uni.getStorageSync(hasMobileKey))
	const isAgent = computed(() => {
		return userInfo.value?.admin_type === 1
	})

	const deviceInfo = wx.getDeviceInfo();

	async function initToken() {
		const token = getTokenSync();
		setToken(token)
	}

	function getTokenSync() {
		return uni.getStorageSync(tokenKey);
	}

	function setToken(tokenStr) {
		if (tokenStr === '') {
			token.value = ''
			uni.removeStorageSync(tokenKey)
		} else {
			token.value = tokenStr
			uni.setStorageSync(tokenKey, tokenStr);
		}
	}

	function setHasMobile(hasMb) {
		if (hasMb === '') {
			hasMobile.value = ''
			uni.removeStorageSync(hasMobileKey)
		} else {
			hasMobile.value = (hasMb === 1 ? true : false)
			uni.setStorageSync(hasMobileKey, hasMobile.value);
		}
	}

	async function initOpenid() {
		const openid = await getOpenid();
		setOpenid(openid)
	}

	function getOpenid() {
		return new Promise(function(resolve, reject) {
			const localOpenId = uni.getStorageSync(openidKey);
			if (localOpenId) {
				resolve(localOpenId)
			} else {
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						const code = loginRes.code
						let appid = 'wx79c3ce95fd9bc29f'
						let secret = ''
						let url =
							`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`
						wx.request({
							url: url,
							success: (res) => {
								let openid = res.data.openid;
								resolve(openid)
							}
						})
					}
				});
			}
		})
	}

	function setOpenid(openidStr) {
		openid.value = openidStr
		uni.setStorageSync(openidKey, openidStr);
	}

	function getUserInfo() {
		return new Promise(resolve => {
			api.getUserInfo().then(res => {
				const data = res.data.data
				uni.setStorageSync(userInfoKey, data);
				userInfo.value = data
			})
		})
	}

	function bindMobile(e) {
		return new Promise((resolve, reject) => {
			if (e.detail.errMsg === "getPhoneNumber:ok") {
				const {
					detail: {
						// encryptedData,
						// iv,
						code
					}
				} = e;
				const params = {
					code
				}
				api.bindMobile(params).then(res => {
					uni.$u.toast('授权成功')
					getUserInfo()
					setHasMobile(1)
					resolve()
				}).catch(err => {
					reject(err)
				})
			} else {
				reject(e.detail.errMsg)
			}

		})
	}

	function login() {
		return new Promise((resolve, reject) => {
			uni.showLoading({
				// title: '登录中...',
				mask: true
			})
			settingIsOk().then(res => {
				uni.getUserInfo({
					desc: '登录数据',
					success(ures) {
						console.log('返回用户信息：', ures)
						uni.login({
							provider: 'weixin',
							success(loginRes) {
								const code = loginRes.code
								let params = {
									code,
									...ures,
								}
								console.log('入参', JSON.stringify(params))

								api.login(params).then(res => {
									console.log('登录返回数据：', res)
									setToken(res.data.data.token)
									setHasMobile(res.data.data
										.hasBindMobile)
									getUserInfo()
									resolve(res)
								}).finally(() => {
									uni.hideLoading()
								})
							}
						})
					}
				})
			}).catch(err => {
				uni.showToast({
					title: '请先授权登录',
					icon: 'none'
				})
				uni.hideLoading()
				reject(err)
			})
		})
	}

	function logout() {
		const pages = getCurrentPages()
		let currentRoute = pages[pages.length - 1].route;
		let currentPath = pages[pages.length - 1]['$page']['fullPath'];
		console.log('currentPath', currentPath)
		setToken('')
		setHasMobile('')
		login().then(() => {
			uni.redirectTo({
				url: currentPath,
			});
		}).catch(() => {
			uni.reLaunch({
				url: '/pages/index/index'
			})
		})
	}

	function settingIsOk() {
		return new Promise((resolve, reject) => {
			uni.getSetting({
				success(res) {
					if (!res.authSetting['scope.userInfo']) {
						uni.authorize({
							scope: 'scope.userInfo',
							success() {
								resolve()
							},
							fail() {
								reject()
							}
						});
					} else {
						resolve()
					}
				}
			});
		})
	}

	return {
		login,
		getUserInfo,
		logout,
		token,
		isLogin,
		hasMobile,
		isAgent,
		openid,
		deviceInfo,
		initToken,
		getTokenSync,
		setToken,
		initOpenid,
		getOpenid,
		setOpenid,
		bindMobile,
	}
})

export default useAppStore